<?php
/**
 * 保存模块配置
 * @param string $app 对应APP  $new_config 修正配置内容
 */
function save_config($app = NULL, $new_config = array()){
    if($app){
        $file = APP_PATH.'/'.$app.'/config.php';
    }else{
        $file = CONFIG_PATH.'config.php';
    }
    if(!file_exists($file)){
        throw new \Exception("APP Config '{$name}' not found", 500);
    }
    if( is_file($file) ) {
        $config = require($file);
        $config = array_merge($config, $new_config);
    }else{
        $config = $new_config;
    }
    $content = var_export($config, true);
    $content = str_replace("_PATH' => '" . addslashes(ROOT_PATH), "_PATH' => ROOT_PATH . '", $content);

    if( file_put_contents($file, "<?php \r\nreturn " . $content . ';' ) ) {
        return true;
    }
    return false;
}
/**
 * 表单处理接口
 * @param  array  $str 要数据数的数据 $delete_value  删除无用数组 $function 回调函数
 * @return array        处理后的数据
 */
function form($str = null, $delete_value = array(), $function = '') {
    if(empty($str))return;
    $str = trim($str);
    list($method,$name) = explode('.',$str,2);
    $method = strtolower($method);
    switch ($method) {
        case 'get':
            $type = $_GET;
            break;
        case 'post':
            $type = $_POST;
            break;
        case 'session':
            $type = $_SESSION;
            break;
        case 'request':
            $type = $_REQUEST;
            break;
        case 'cookie':
            $type = $_COOKIE;
            break;
        default:
            return ;
    }
    if(empty($name)){
        $request = $type;
    }else{
        switch ($method) {
            case 'get':
                $request = urldecode($type[$name]);
                break;
            default:
                $request = $type[$name];
                break;
        }
    }
    $request = filter_string($request,$delete_value);
    if(!empty($name) && !empty($function)){
        $request = call_user_func($function,$request);
    }
    return $request;
}
/**
 * 过滤数据
 * @param  array  $form_array 需要过滤的数组 $delete_value  删除无用数组
 * @return array  过滤后的数据
 */
function filter_string($form_array,$delete_value = array(),$decode = 0){
    if($form_array===NULL)return false;
    if (is_array($form_array)){
        $default_delete = array('action','button','submit');
        $clear_array = array_merge($default_delete,$delete_value);
        foreach ($form_array as $key => $value){
            if(!in_array($key,$clear_array)){
                $data[$key] = filter_string($value,array(),$decode);
            }
        }
        return $data;
    }else{
        if($decode){
            return htmlspecialchars_decode($form_array,ENT_QUOTES);
        }else{
            return htmlspecialchars(trim($form_array),ENT_QUOTES, 'UTF-8');
        }
    }
}

/**
 * 前台标签调用函数
 * $labelID：标签ID，$ClassID：栏目ID, $function：回调函数
 * @return array
 */
function label($labelID,$ClassID,$page = NULL){
    $labelID   = intval($labelID);
    $ClassID   = intval($ClassID);
    $rel = model('label','cms')->_find(array('id'=> $labelID));
    if($rel){
        if($rel['type'] == 1){
            return model('channel','cms')->Label($rel,$ClassID);
        }elseif($rel['type'] == 2){
            return model('index','cms')->Label($rel,$ClassID,$page);
        }else{
            echo 'SQL标签参数出错!';
        }
    }else{
        return array();
    }
}
/**
 * 分页结果显示
 * @return string  字符串
 */
function getPage($pager,$action = array()){
    $pageArray = $pager;
    if(is_array($pageArray)){
        $html = '<ul class="pager"><li><a href="'.GreatePageUrl($pageArray['firstPage'],$action).'" >首页</a></li>
                <li><a href="'.GreatePageUrl($pageArray['prevPage'],$action).'">上一页</a></li> ';
            foreach ($pageArray['allPages'] as $value) {
                if($value){
                    if($value == $pageArray['page']){
                        $html .= '<li class="active">';
                    }else{
                        $html .= '<li>';
                    }
                    $html .= '<a href="'.GreatePageUrl($value,$action).'">'.$value.'</a></li>';
                }        
           }
         $html .= '<li><a href="'.GreatePageUrl($pageArray['nextPage'],$action).'">下一页</a></li>
          <li><a href="'.GreatePageUrl($pageArray['lastPage'],$action).'">末页</a></li></ul>';
    }
    return $html;
}
//分页URL处理
function GreatePageUrl($page,$action = array()){
    $ary_page = array('page' => $page);
    if($action){
        $ary_page = array_merge($ary_page,$action);
    }
    return url( APP_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME,$ary_page);
}

/**
 * 认证查询
 * @return string  字符串
 */
function dev(){
    return \framework\ext\Util::cpDecode('2fadVMwbhHc5Bkdjp3/09B7So2AQhtbk85jNkyLKb7TarbXNvgmXchHiU81Ruazz7nHcDNpuXuOSQ6P6Zg','siteplus');
}

//获取客户端IP
function get_client_ip(){
    return \framework\ext\Util::getIp();
}

//字符串截取
function len($str, $len=0){
    if(!empty($len)){
        return \framework\ext\Util::msubstr($str, 0, $len);
    }else{
        return $str;
    }
}
//浏览器友好的变量输出
function dump($var, $exit=false){
    $output = print_r($var, true);
    $output = "<pre>" . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
    echo $output;
    if($exit) exit();
}

//获取微秒时间，常用于计算程序的运行时间
function utime(){
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}
/**
 * 调试运行时间和占用内存
 * @return string   微秒
 */
function debug($flag='system', $end = false){
    static $arr =array();
    if( !$end ){
        $arr[$flag] = microtime(true); 
    } else if( $end && isset($arr[$flag]) ) {
        echo  '<p>' . $flag . ': runtime:' . round( (microtime(true) - $arr[$flag]), 6)
             . '    memory_usage:' . memory_get_usage()/1000 . 'KB</p>'; 
    }
}

/**
 * 获取文件或文件大小
 * @param string $directoty 路径
 * @return int
 */
function dir_size($directoty){
    $dir_size = 0;
    if ($dir_handle = @opendir($directoty)) {
        while ($filename = readdir($dir_handle)) {
            $subFile = $directoty . DIRECTORY_SEPARATOR . $filename;
            if ($filename == '.' || $filename == '..') {
                continue;
            } elseif (is_dir($subFile)) {
                $dir_size += dir_size($subFile);
            } elseif (is_file($subFile)) {
                $dir_size += filesize($subFile);
            }
        }
        closedir($dir_handle);
    }
    return ($dir_size);
}

/* *
 * 方法库-获取随机值
 * @return string  
* */
function random_str($str,$len){
    return substr(md5(uniqid(rand()*strval($str))),0, (int) $len);
}

/**
 * 生成唯一字符串(数字)
 * @return string  字符串
 */
function unique_str(){
    return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0,8);
}

/* *
 * 生成唯一的订单号 20110809111259232312
 * 2011-年日期
 * 08-月份
 * 09-日期
 * 11-小时
 * 12-分
 * 59-秒
 * 2323-微秒
 * 12-随机值
 * @return string
 */
function trade_no() {
    list($usec, $sec) = explode(" ", microtime());
    $usec = substr(str_replace('0.', '', $usec), 0 ,4);
    $str  = rand(10,99);
    return date("YmdHis").round($usec).$str;
}

/**
 * 方法库-获取随机Hash值 
 * @return string
 */
function get_hash($length = 13) { 
    $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($chars) - 1;
    mt_srand((double)microtime() * 1000000);
    for ($i=0; $i<$length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}